package com.simon.study.algorithm.zheda;

import lombok.Getter;
import lombok.NoArgsConstructor;

/**
 * <p>
 *
 * @author simon
 */
public class UnionSet {

    @NoArgsConstructor @Getter
    public static class DataSet{
        int     data;
        int     pidx;

        public DataSet(int data) {
            this.data = data;
        }
    }

    DataSet[]   datas;
    int         capacity;


    public UnionSet(int capacity) {
        this.capacity   = capacity;
        this.datas      = new DataSet[this.capacity];
    }

    public int find(int x){
        int i = 0;
        for (; i < datas.length && datas[i].data != x; i++);

        if(datas.length <= i){ return -1; }

        for(; datas[i].pidx > 0; i = datas[i].pidx );

        return i;
    }


    public void union(int x, int y){
        int xroot = find(x);
        int yroot = find(y);

        if(xroot != yroot){ datas[xroot].pidx = yroot; }
    }
}
